//
//  SeatViewController.m
//  EPBPro
//
//  Created by wucha on 2018/6/13.
//  Copyright © 2018年 fc. All rights reserved.
//

#import "SeatViewController.h"
#import "POIAnnotation.h"
#import "MachineListViewController.h"
#import "CityChangeViewController.h"
#import "HttpEquipmentAction.h"
#import "EquipmentInfo.h"
#import "EquipmentAnnotation.h"
#import "AreaInfo.h"
#import "AddEquipmentViewController.h"
#import "MachineDetailViewController.h"

@interface SeatViewController ()<MAMapViewDelegate,UITextFieldDelegate>{
    
}
@property (nonatomic, strong) AreaInfo *areaInfo;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) NSArray *listArray;
@property (nonatomic, strong) UIButton *cityButton;
@property (nonatomic, strong) NSArray *equipmentArray;
@property (nonatomic, strong) NSMutableArray *anotationArray;
@end

@implementation SeatViewController

-(id)init{
    if (self == [super init]) {
        AreaInfo *areaInfo = [[AreaInfo alloc] init];
        areaInfo.name = @"苏州市";
        areaInfo.code = @"3205";
        self.areaInfo = areaInfo;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *cityButton = [UIButton new];
    [cityButton setTitleColor:DefaultBlueColor forState:UIControlStateNormal];
    [cityButton setTitle:@"苏州市" forState:UIControlStateNormal];
    cityButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    cityButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cityButton addTarget:self action:@selector(cityChangeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cityButton];
    cityButton.sd_layout.topSpaceToView(self.view, StatusBarHeight).leftSpaceToView(self.view, 15).widthIs(50).heightIs(44);
    self.cityButton = cityButton;
    
    UIImageView *backImageView = [UIImageView new];
    backImageView.userInteractionEnabled = YES;
    backImageView.backgroundColor = HexRGB(0xE6E6E6);
    backImageView.layer.cornerRadius = 15;
    [self.view addSubview:backImageView];
    backImageView.sd_layout.leftSpaceToView(cityButton, 20).rightSpaceToView(self.view, 20).topSpaceToView(self.view, StatusBarHeight+7).heightIs(30);
    
    UIImageView *searchImageView = [UIImageView new];
    searchImageView.image = [UIImage imageNamed:@"machine_search1"];
    searchImageView.contentMode = UIViewContentModeCenter;
    [backImageView addSubview:searchImageView];
    searchImageView.sd_layout.leftSpaceToView(backImageView, 10).topSpaceToView(backImageView, 0).bottomSpaceToView(backImageView, 0).widthIs(25);
    
    UITextField *nameTextField = [UITextField new];
    nameTextField.font = [UIFont systemFontOfSize:14];
    nameTextField.placeholder = @"搜索机位";
    [backImageView addSubview:nameTextField];
    nameTextField.sd_layout.leftSpaceToView(searchImageView, 10).rightSpaceToView(backImageView, 10).topSpaceToView(backImageView, 0).bottomSpaceToView(backImageView, 0);
    nameTextField.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    nameTextField.delegate = self;//设置代理
    self.listArray = @[@"可租广告位",@"已租广告位",@"维修广告位"];
    
    BOOL flag = [Utils getUserPermission:@"addmachine"];
    if(flag){
        UIButton *addEButton = [UIButton new];
        addEButton.backgroundColor = DefaultBlueColor;
        [addEButton addTarget:self action:@selector(addEquipmentAction:) forControlEvents:UIControlEventTouchUpInside];
        [addEButton setTitle:@"添加机位" forState:UIControlStateNormal];
        [self.view addSubview:addEButton];
        addEButton.sd_layout.leftSpaceToView(self.view, 0).bottomSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).heightIs(44);
    }
    

    self.tableView.tableHeaderView = [self getHeaderView];
    self.tableView.separatorStyle = 0;
    self.anotationArray = [NSMutableArray array];
    NSMutableArray *mutableArray = [NSMutableArray array];
    NSValue *value1 = [NSValue valueWithCGPoint:CGPointMake(31.323635, 120.714587)];
    NSValue *value2 = [NSValue valueWithCGPoint:CGPointMake(31.303413, 120.650527)];
    NSValue *value3 = [NSValue valueWithCGPoint:CGPointMake(31.277558, 120.637781)];
    NSValue *value4 = [NSValue valueWithCGPoint:CGPointMake(31.231369, 120.587742)];
    [mutableArray addObject:value1];
    [mutableArray addObject:value2];
    [mutableArray addObject:value3];
    [mutableArray addObject:value4];
    
    for (int i =0;i<mutableArray.count;i++ ) {
        NSValue *value1 = mutableArray[i];
        EquipmentAnnotation *a1 = [[EquipmentAnnotation alloc] init];
        a1.coordinate = CLLocationCoordinate2DMake([value1 CGPointValue].x, [value1 CGPointValue].y);
        a1.title      = [NSString stringWithFormat:@"垃圾箱 %d", i];
        [_anotationArray addObject:a1];
    }
//    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(31.323635, 120.714587) animated:YES];
//    [self.mapView setZoomLevel:15];
    [self.mapView addAnnotations:_anotationArray];

    [self.mapView setVisibleMapRect:[CommonUtility minMapRectForAnnotations:_anotationArray]];

    NSLog(@"%f",    self.mapView.zoomLevel);
    [self.mapView setZoomLevel:self.mapView.zoomLevel-0.25];
    [self loadData:@"苏州市"];
    

}

-(void)addEquipmentAction:(id)sender{
    AddEquipmentViewController *addEquipmentViewController = [[AddEquipmentViewController alloc] init];
    [self.navigationController pushViewController:addEquipmentViewController animated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.mapView) {
        [self loadData:@"苏州市"];
    }
}

#pragma mark- UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField

{
    [textField resignFirstResponder];
    return YES;
    
}

-(void)reloadMapView:(NSArray*)equipmentArray{
    [self.mapView removeAnnotations:_anotationArray];
    [_anotationArray removeAllObjects];
    for (EquipmentInfo *equipmentInfo in equipmentArray) {
        
        EquipmentAnnotation *a1 = [[EquipmentAnnotation alloc] init];
        a1.coordinate = CLLocationCoordinate2DMake([equipmentInfo.latitude floatValue],[equipmentInfo.longitude floatValue]);
        a1.status = equipmentInfo.status;
        a1.title = equipmentInfo.code;
        a1.equipmentId = equipmentInfo.id;
        [_anotationArray addObject:a1];
    }
    [self.mapView addAnnotations:_anotationArray];
    if (_anotationArray.count == 1) {
        EquipmentInfo *equipmentInfo = equipmentArray[0];
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake([equipmentInfo.latitude floatValue],[equipmentInfo.longitude floatValue]) animated:YES];

    }else{
        [self.mapView setVisibleMapRect:[CommonUtility minMapRectForAnnotations:_anotationArray]];
        [self.mapView setZoomLevel:self.mapView.zoomLevel-0.25];
    }
    
}

-(void)loadData:(NSString*)city{
    EquipmentActionInfo *equipmentActionInfo = [[EquipmentActionInfo alloc] init];
    equipmentActionInfo.city = city;
    [HttpEquipmentAction getEquipmentSimpleList:equipmentActionInfo block:^(id result, NSError *error) {
        if (!error) {
            NSArray *array = result;
            self.equipmentArray = array;
            [self reloadMapView:array];
            [self.tableView reloadData];
        }
    }];
}

-(void)cityChangeAction:(id)sender{
    CityChangeViewController *cityChangeViewController = [[CityChangeViewController alloc] initWithBlock:^(AreaInfo *areaInfo) {
        self.areaInfo = areaInfo;
        [self.cityButton setTitle:areaInfo.name forState:UIControlStateNormal];
        [self loadData:areaInfo.name];

    }];
    [self.navigationController pushViewController:cityChangeViewController animated:YES];
}

-(UIView*)getHeaderView{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
    MAMapView *mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
    //    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    mapView.delegate = self;
//    [self.view addSubview:self.mapView];
    mapView.showsCompass = NO;
    self.mapView = mapView;
    return mapView;
}

-(int)getEquipmentNumber:(NSArray*)array andStatus:(NSString*)status{
    int i=0;
    for (EquipmentInfo *equipmentInfo in array) {
        if ([equipmentInfo.status isEqualToString:status]) {
            i++;
        }
    }
    
    return i;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = 0;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        UIView *lineView = [UIView new];
        lineView.tag = 10;
        lineView.backgroundColor = DefaultCellLineColor;
        [cell.contentView addSubview:lineView];
        lineView.sd_layout.leftSpaceToView(cell.contentView, 10).bottomSpaceToView(cell.contentView, 0).widthIs(SCREEN_WIDTH-10).heightIs(1);
    }
    // Configure the cell...
    UIView *lineView = [cell.contentView viewWithTag:10];
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"machine_yellow"];
        lineView.hidden = NO;
        cell.textLabel.text = [NSString stringWithFormat:@"%@(%d)",self.listArray[indexPath.row],[self getEquipmentNumber:self.equipmentArray andStatus:@"open"]];

    }
    else if(indexPath.row == 1){
        cell.imageView.image = [UIImage imageNamed:@"machine_blue"];
        lineView.hidden = NO;
        cell.textLabel.text = [NSString stringWithFormat:@"%@(%d)",self.listArray[indexPath.row],[self getEquipmentNumber:self.equipmentArray andStatus:@"renting"]];

    }else{
        cell.imageView.image = [UIImage imageNamed:@"machine_red"];
        lineView.hidden = YES;
        cell.textLabel.text = [NSString stringWithFormat:@"%@(%d)",self.listArray[indexPath.row],[self getEquipmentNumber:self.equipmentArray andStatus:@"maintaining"]];

    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIViewController *machineViewController = nil;
    if (indexPath.row == 0) {
        machineViewController = [[MachineListViewController alloc] initWithStatus:@"open" withAreaInfo:self.areaInfo];
    }else if (indexPath.row == 1){
        machineViewController = [[MachineListViewController alloc] initWithStatus:@"renting" withAreaInfo:self.areaInfo];

    }else{
        machineViewController = [[MachineListViewController alloc] initWithStatus:@"maintaining" withAreaInfo:self.areaInfo];

    }
    
    [self.navigationController pushViewController:machineViewController animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - MAMapViewDelegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[EquipmentAnnotation class]])
    {
        static NSString *animatedAnnotationIdentifier = @"AnimatedAnnotationIdentifier";
        
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:animatedAnnotationIdentifier];
        
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                                reuseIdentifier:animatedAnnotationIdentifier];
            
            annotationView.canShowCallout   = YES;
            annotationView.draggable        = YES;
            annotationView.image = [UIImage imageNamed:@"machine_red"];
        }
        EquipmentAnnotation *eqAnnotation = annotation;
        if ([eqAnnotation.status isEqualToString:@"open"]) {
            annotationView.image = [UIImage imageNamed:@"local_yellow"];

        }else if ([eqAnnotation.status isEqualToString:@"renting"]){
            annotationView.image = [UIImage imageNamed:@"local_blue"];

        }else{
            annotationView.image = [UIImage imageNamed:@"local_red"];

        }
        
        
        return annotationView;
    }
    
    return nil;


}

- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view{
    EquipmentAnnotation *eqAnnotation = view.annotation;
    [HttpEquipmentAction getSingleEquipmentInfo:eqAnnotation.equipmentId block:^(id result, NSError *error) {
        if (!error) {
            MachineDetailViewController *machineDetailViewController = [[MachineDetailViewController alloc] initWithEquipmentInfo:result];
            [self.navigationController pushViewController:machineDetailViewController animated:YES];
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
